package com.sunspring.zdcall.controller.commoncontroller;

import com.sunspring.zdcall.common.SimpleResponse;
import com.sunspring.zdcall.common.exception.ZdException;
import com.sunspring.zdcall.entity.ZdBaseHospital;
import com.sunspring.zdcall.param.HospitalParam;
import com.sunspring.zdcall.service.HospitalService;
import com.sunspring.zdcall.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;

/**
 * @author wulei
 * @date 2019-01-14
 **/
@RestController
@RequestMapping("/sys/hospital")
public class HospitalController {

    @Autowired
    private HospitalService hs;

    /**
     * 查看医院信息
     */
    @GetMapping("/info")
    public SimpleResponse info() {
        ZdBaseHospital hospital = hs.getHospitalInfo();
        //拼接图片地址
        if (hospital != null) {
            hospital.setHospitalLogo(FileUtil.spliceAddress(hospital.getHospitalLogo()));
        }
        return SimpleResponse.success(hospital);
    }

    /**
     * 新增医院信息
     * @param hospital HospitalParam
     */
    @PostMapping("/add")
    public SimpleResponse add(@Valid HospitalParam hospital, BindingResult result) throws IOException {
        if (result.hasErrors()) {
            throw new ZdException(Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        }
        hs.addHospital(hospital);
        return SimpleResponse.success();
    }

    /**
     * 修改医院信息
     * @param hospital HospitalParam
     */
    @PostMapping("/update")
    public SimpleResponse update(HospitalParam hospital) throws IOException {
        hs.updateHospital(hospital);
        return SimpleResponse.success();
    }

}
